const FormData = require("form-data");
const url = require("url");
const fs = require("fs");

/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{
 * etag:String}}>}
 * @param {String} file_fullpath 
 * @param {String} key 
 * @param {String} policy 
 * @param {String} access_key_id 
 * @param {String} signature 
 * @param {String} huawei_domain
 */
function normalFormDataPost(file_fullpath, key, policy, access_key_id, signature, huawei_domain) {
  return new Promise(resolve => {
    let form = new FormData;
    form.append("key", key);
    form.append("policy", policy);
    form.append("AccessKeyId", access_key_id);
    form.append("signature", signature);
    form.append("success_action_status", 201);
    form.append("file", fs.createReadStream(file_fullpath), {
      contentType: "application/vnd.openxmlformat",
      filename: `${Math.random()}.docx`
    });
    form.submit(`https://${huawei_domain}/`, (err, response) => {
      if (err) {
        return resolve({
          ok: false,
          msg: `err:${err.message}`
        })
      }
      if (!response.statusCode == 201) {
        return resolve({
          ok: false,
          msg: `status is NOT 201:${response.statusCode}/${response.statusMessage}`
        })
      }
      if (!response.headers.etag) {
        return resolve({
          ok: false,
          msg: `response does not have a etag`
        })
      }
      /**@type {string} */
      let etag_raw = response.headers.etag;
      let etag = etag_raw.replace(/\"/g, "")
      return resolve({
        ok: true,
        msg: "ok",
        data:{
          etag:etag
        }
      })
    })


  })
}


module.exports = {
  normalFormDataPost
}